package elitech.vietnam.weatherfashion.tabs.self;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshGridView2;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

import elitech.vietnam.weatherfashion.R;
import elitech.vietnam.weatherfashion.WFApplication;
import elitech.vietnam.weatherfashion.config.Const;
import elitech.vietnam.weatherfashion.config.GlobalValue;
import elitech.vietnam.weatherfashion.config.Utils;
import elitech.vietnam.weatherfashion.custom.dialogues.DialogUserInfo;
import elitech.vietnam.weatherfashion.custom.dialogues.PicPickerDialog;
import elitech.vietnam.weatherfashion.custom.dialogues.TimeOutDialog;
import elitech.vietnam.weatherfashion.custom.multicolumnlistview.MultiColumnListView;
import elitech.vietnam.weatherfashion.dto.MemberDTO;
import elitech.vietnam.weatherfashion.dto.PostDTO;
import elitech.vietnam.weatherfashion.service.PHPSoapServiceCaller;
import elitech.vietnam.weatherfashion.tabs.AbstractFragment;

public class SelfFragment extends AbstractFragment implements View.OnClickListener, OnRefreshListener2<MultiColumnListView> {

	private PullToRefreshGridView2 mGridView;
	private SelfGridAdapter mAdapter;
	private Button button_camera;
	private ImageView image_useravatar;
	private TextView text_username, text_userstatus;

	boolean isPullUp = false;
	List<PostDTO> data = null;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.tab_self, null);
		setupView(view);

		mGridView = (PullToRefreshGridView2) view.findViewById(R.id.layout_main);
		image_useravatar = (ImageView) view.findViewById(R.id.self_image_useravatar);
		text_username = (TextView) view.findViewById(R.id.self_textview_username);
		text_userstatus = (TextView) view.findViewById(R.id.self_textview_userstatus);
		button_camera = (Button) view.findViewById(R.id.self_button_camera);

		button_camera.setOnClickListener(this);

		if (!isAdded())
			return null;

		return view;
	}
	
	@Override
	public void onPause() {
		super.onPause();
		mGridView.onRefreshComplete();
	}

	@Override
	public void onResume() {
		Utils.Log("Self Resume...");
		super.onResume();
		MemberDTO user = GlobalValue.getInstance(getActivity()).readUserInfo();
		if (!isAdded() || user == null)
			return;

		loadMember();

		if (getActivity().getIntent().getIntExtra("SELF_RELOAD", -1) > 0 || WFApplication.getInstance().selfData == null || WFApplication.getInstance().selfData.isEmpty())
			new SelfLoadingTask().execute();
		else
			loadPosts();

		if (mAdapter != null)
			mAdapter.notifyDataSetChanged();

	}

	@Override
	public void onDestroyView() {
		mAdapter = null;
		mGridView = null;
		super.onDestroyView();
	}

	public void loadMember() {
		// ImageLoader.getInstance().displayImage(AppConfig.SERVER_IMAGE_URL +
		// AppConfig.getInstance().appUser.getMemberPic(), image_useravatar);
		MemberDTO user = GlobalValue.getInstance(getActivity()).readUserInfo();
		UrlImageViewHelper.setUrlDrawable(image_useravatar, Const.SERVER_IMAGE_URL + user.getMemberPic(), R.drawable.no_avatar);
		text_username.setText(user.getMemberName());
		text_userstatus.setText(user.getMemberProfile());
		image_useravatar.setOnClickListener(this);
	}

	public void loadPosts() {
		if (mGridView == null || WFApplication.getInstance().selfData == null)
			return;

		if (WFApplication.getInstance().selfData == null || WFApplication.getInstance().selfData.isEmpty()) {
			onNoData(true);
			return;
		}
		getActivity().getIntent().removeExtra("SELF_RELOAD");
		onNoData(false);
		
		data = new ArrayList<PostDTO>();
		data.addAll(WFApplication.getInstance().selfData);

		mGridView.setMode(Mode.PULL_FROM_END);
		mGridView.setOnRefreshListener(this);
		
		mAdapter = new SelfGridAdapter(SelfFragment.this, R.layout.styler_grid_item, data);
		mGridView.setAdapter(mAdapter);
	}

	@Override
	public void onClick(View arg0) {
		MemberDTO user = GlobalValue.getInstance(getActivity()).readUserInfo();
		switch (arg0.getId()) {

		case R.id.self_button_camera:

			if (user == null) {
				Utils.openLogin(getActivity());
			} else
				new PicPickerDialog(getActivity(), this).show();
			break;

		case R.id.self_image_useravatar:
			new DialogUserInfo(getActivity(), user).show();
			break;
		default:
			break;
		}
	}

	class SelfLoadingTask extends AsyncTask<Integer, Integer, Boolean> {
		@Override
		protected Boolean doInBackground(Integer... params) {
			try {
				Utils.getSelfData(getActivity());
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
			return null;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			MemberDTO user = GlobalValue.getInstance(getActivity()).readUserInfo();
			if (!isAdded() || user == null)
				return;
			onLoading(true);
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			MemberDTO user = GlobalValue.getInstance(getActivity()).readUserInfo();
			if (!isAdded() || user == null)
				return;
			onLoading(false);
			if (result != null) {
				new TimeOutDialog(getActivity()).show();
				return;
			}
			loadPosts();
		}
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<MultiColumnListView> refreshView) {
		new LoadMoreItem().execute();
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<MultiColumnListView> refreshView) {
		new LoadMoreItem().execute();
	}
	
	class LoadMoreItem extends AsyncTask<Integer, Integer, List<PostDTO>> {
		@Override
		protected List<PostDTO> doInBackground(Integer... params) {
			PHPSoapServiceCaller service = new PHPSoapServiceCaller();
			MemberDTO user = GlobalValue.getInstance(getActivity()).readUserInfo();
			int n = (user != null) ? user.getId() : -1;
			List<PostDTO> list = null;
			try {
				list = service.getFashionMemberLikeCountry(n, n, Const.COUNTRY_CODE, data.size(), Const.LOADMORE_PAGE_ITEMCOUNT);
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}
			return list;
		}
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		@Override
		protected void onPostExecute(List<PostDTO> result) {
			super.onPostExecute(result);
			if (mGridView != null)
				mGridView.getLoadingLayoutProxy();
			if (result == null) {
				new TimeOutDialog(getActivity()).show();
				return;
			}
			if (result.isEmpty()) {
				if (mGridView != null) {
					mGridView.setMode(Mode.DISABLED);
					mGridView.setOnRefreshListener((OnRefreshListener2<MultiColumnListView>)null);
				}
				return;
			}
			if (data != null)
				data.addAll(result);
			if (mAdapter != null)
				mAdapter.notifyDataSetChanged();
		}
	}
}
